package heap

import "lesson01/classfile"

// ClassMember 字段和方法都属于类的成员，它们有一些相同的信息（访问标志、名字、描述符）
type ClassMember struct {
	accessFlags uint16
	name        string
	descriptor  string
	class       *Class
}

func (e *ClassMember) copyMemberInfo(memberInfo *classfile.MemberInfo) {
	e.accessFlags = memberInfo.AccessFlags()
	e.name = memberInfo.Name()
	e.descriptor = memberInfo.Descriptor()
}

func (e *ClassMember) IsPublic() bool {
	return e.accessFlags&ACC_PUBLIC == ACC_PUBLIC
}

func (e *ClassMember) IsPrivate() bool {
	return e.accessFlags&ACC_PRIVATE == ACC_PRIVATE
}

func (e *ClassMember) IsProtected() bool {
	return e.accessFlags&ACC_PROTECTED == ACC_PROTECTED
}

func (e *ClassMember) IsStatic() bool {
	return e.accessFlags&ACC_STATIC == ACC_STATIC
}

func (e *ClassMember) IsFinal() bool {
	return e.accessFlags&ACC_FINAL == ACC_FINAL
}

// Name get
func (e *ClassMember) Name() string {
	return e.name
}

func (e *ClassMember) Descriptor() string {
	return e.descriptor
}

func (e *ClassMember) Class() *Class {
	return e.class
}

func (e *ClassMember) isAccessibleTo(other *Class) bool {
	if e.IsPublic() {
		return true
	}
	class := e.class
	if e.IsProtected() {
		return class == other || other.IsSubClassOf(class) ||
			class.GetPackageName() == other.GetPackageName()
	}

	if !e.IsPrivate() {
		return class.GetPackageName() == other.GetPackageName()
	}

	return other == class
}
